#include <Arduino.h>
#include <Wire.h>

#include "sensirion_common.h"
#include "sgp30.h"

void setup(void)
{
  Serial.begin(115200);
  Wire.setPins(7, 6); // 统一设置底层wire
}

void loop()
{
  u16 i = 0;
  s16 err;
  u16 tvoc_ppb, co2_eq_ppm;
  u32 iaq_baseline;
  u16 scaled_ethanol_signal, scaled_h2_signal;

  /* Busy loop for initialization. The main loop does not work without
   * a sensor. */
  while (sgp_probe() != STATUS_OK)
  {
    Serial.printf("SGP sensor probing failed\n");
  }
  /* printf("SGP sensor probing successful\n"); */

  /* Read gas signals */
  err = sgp_measure_signals_blocking_read(&scaled_ethanol_signal,
                                          &scaled_h2_signal);
  if (err == STATUS_OK)
  {
    /* Print ethanol signal with floating point support */
    Serial.printf("Ethanol signal: %f\n", scaled_ethanol_signal / 512.0f);

    /* Print H2 signal without floating point support */
    Serial.printf("H2 signal: %u.%09llu\n", scaled_h2_signal >> 9,
                  ((scaled_h2_signal & 0x01ff) * (u64)1000000000) >> 9);
  }
  else
  {
    Serial.printf("error reading signals\n");
  }

  /* Consider the two cases (A) and (B):
   * (A) If no baseline is available or the most recent baseline is more than
   *     one week old, it must discarded. A new baseline is found with
   *     sgp_iaq_init() */
  err = sgp_iaq_init();
  /* (B) If a recent baseline is available, set it after sgp_iaq_init() for
   * faster start-up */
  /* IMPLEMENT: retrieve iaq_baseline from presistent storage;
   * err = sgp_set_iaq_baseline(iaq_baseline);
   */

  /* Run periodic IAQ measurements at defined intervals */
  while (1)
  {
    err = sgp_measure_iaq_blocking_read(&tvoc_ppb, &co2_eq_ppm);
    if (err == STATUS_OK)
    {
      Serial.printf("tVOC  Concentration: %dppb\n", tvoc_ppb);
      Serial.printf("CO2eq Concentration: %dppm\n", co2_eq_ppm);
    }
    else
    {
      Serial.printf("error reading IAQ values\n");
    }

    /*
     * IMPLEMENT: get absolute humidity to enable humidity compensation
     * u32 ah = get_absolute_humidity(); // absolute humidity in mg/m^3
     * sgp_set_absolute_humidity(ah);
     */

    /* Persist the current baseline every hour */
    if (++i % 3600 == 3599)
    {
      err = sgp_get_iaq_baseline(&iaq_baseline);
      if (err == STATUS_OK)
      {
        /* IMPLEMENT: store baseline to presistent storage */
      }
    }

    /* The IAQ measurement must be triggered exactly once per second (SGP30)
     * to get accurate values.
     */
    /* sleep(1); // SGP30 */
    delay(1000);
  }
}